﻿using Microsoft.EntityFrameworkCore;
using System.Linq.Expressions;

namespace Repository.communal
{
    public class BaseRepository<T> : IBaseRepository<T> where T : class, new()
    {
        public BaseRepository(MyDbContext myDb)
        {
            MyDb = myDb;
        }

        public MyDbContext MyDb { get; }

        public async Task<int> AddAsync(T t)
        {
            await MyDb.AddAsync(t);
            return await MyDb.SaveChangesAsync();
        }

        public async Task<int> AddRange(T t)
        {
            await MyDb.AddRangeAsync(t);
            return await MyDb.SaveChangesAsync();
        }

        public async Task<List<T>> GetAllAsync()
        {
            return await MyDb.Set<T>().ToListAsync();
        }

        public async Task<List<T>> GetAsync(Expression<Func<T, bool>> expre)
        {
            return await MyDb.Set<T>().Where(expre).ToListAsync();
        }

        public async Task<T> GetModelAsync(int id)
        {
            return await MyDb.Set<T>().FindAsync(id);
        }

        public async Task<int> Update(T t)
        {
            MyDb.Update(t);
            return await MyDb.SaveChangesAsync();
        }


        /// <summary>
        /// 批量添加
        /// </summary>
        /// <param name="entity">添加数组</param>
        /// <returns>返回受影响行数</returns>
        public async Task<int> BatchAdd(List<T> entity)
        {
            await MyDb.Set<T>().AddRangeAsync(entity);
            return await MyDb.SaveChangesAsync();
        }

        /// <summary>
        /// 批量修改
        /// </summary>
        /// <param name="entity">修改数组</param>
        /// <returns>返回受影响行数</returns>
        public async Task<int> BatchUpdate(List<T> entity)
        {
            MyDb.Set<T>().UpdateRange(entity);
            return await MyDb.SaveChangesAsync();
        }
    }
}
